package cn.itsource.ymcc.consumer;

import cn.itsource.result.JSONResult;
import cn.itsource.util.AssertUtil;
import cn.itsource.ymcc.constant.MQ;
import cn.itsource.ymcc.domain.MediaFile;
import cn.itsource.ymcc.service.IMediaFileService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQ.TOPIC_VIDEO_PUSH_SRS,
        selectorExpression = MQ.TAGS_VIDEO_PUSH_SRS,
        consumerGroup = "VideoPushMessageConsumer")
public class VideoPushMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMediaFileService mediaFileService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            //获取到消息内容
            byte[] body = messageExt.getBody();
            //非空校验
            AssertUtil.isTrue(body != null && body.length >0,"VideoPushMessageConsumer获取到的消息为空！！！");
            //将内容装为String字符串
            String s = new String(body, "utf-8");
            //将json字符串转为MediaFile实体类对象形式
            MediaFile mediaFile = JSON.parseObject(s, MediaFile.class);
           // log.info("正在将json字符串转化为MediaFile对象...............");

            //调用方法 文件推流到SRS服务器
            JSONResult jsonResult = mediaFileService.handleFile2m3u8(mediaFile);
            AssertUtil.isTrue(jsonResult.getSuccess(),"视频推流失败！！！");
           // log.info("视频文件异步推流已完成.......");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
